package logic

import (
	"book/bookrpc/bookrpc"
	"book/bookrpc/internal/svc"
	"book/models/mysql"
	"context"
	"fmt"
	"gorm.io/gorm"

	"github.com/zeromicro/go-zero/core/logx"
)

type PerfectLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPerfectLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PerfectLogic {
	return &PerfectLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *PerfectLogic) Perfect(in *bookrpc.PerfectRequest) (*bookrpc.PerfectResponse, error) {
	// todo: add your logic here and delete this line

	user := mysql.User{
		Model:   gorm.Model{ID: uint(in.UserId)},
		Name:    in.Name,
		Address: in.Address,
		Image:   in.Image,
	}

	begin := mysql.DB.Debug().Begin()

	err := begin.Updates(&user).Error

	if err != nil {
		begin.Rollback()
		return nil, fmt.Errorf("当前数据修改失败")
	}

	//如果我传入身份证号的时候
	if in.IdCard != "" {
		//我通过我的用户id去数据库查一下我之前有没有进行过实名
		var userCard mysql.UserIdCard
		err := begin.Where("user_id = ?", in.UserId).Find(&userCard).Error

		if err != nil {
			begin.Rollback()
			return nil, fmt.Errorf("当前数据修改过程失败")
		}

		//如果没有实名过  我将给身份证表中增加一条数据
		if userCard.ID == 0 {
			card := mysql.UserIdCard{
				UserId:   in.UserId,
				IdCard:   in.IdCard,
				RealName: in.RealName,
			}

			err := begin.Create(&card).Error

			if err != nil {
				begin.Rollback()
				return nil, fmt.Errorf("当前数据修改过程失败")
			}
		} else {
			//如果实名过了  那我把实名过的身份证以及真实姓名进行修改
			userCard.IdCard = in.IdCard
			userCard.RealName = in.RealName
			err := begin.Updates(&userCard).Error

			if err != nil {
				begin.Rollback()
				return nil, fmt.Errorf("当前数据修改过程失败")
			}
		}
	}

	begin.Commit()

	return &bookrpc.PerfectResponse{
		UserId: int64(user.ID),
	}, nil
}
